function createShader(gl: WebGLRenderingContext, type: number, source: string): WebGLShader {
    let shader = gl.createShader(type)!;
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    let ok = gl.getShaderParameter(shader, gl.COMPILE_STATUS)
    if (ok) {
        return shader;
    }
    let err = gl.getShaderInfoLog(shader);
    gl.deleteShader(shader)
    throw new Error('error:' + err)
}

function createProgram(gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader): WebGLProgram {
    let program = gl.createProgram()!;
    gl.attachShader(program, vertexShader);
    gl.attachShader(program, fragmentShader);
    gl.linkProgram(program);

    let ok = gl.getProgramParameter(program, gl.LINK_STATUS)
    if (ok) {
        return program;
    }
    let err = gl.getProgramInfoLog(program);
    gl.deleteProgram(program)
    throw new Error('error:' + err)
}

const vertexSource = `
attribute vec2 a_position;
uniform vec2 a_rect;

varying vec2 v_pos;

void main() {
    vec2 clip_space = (a_position.xy / a_rect) * 2.0 - 1.0;

    v_pos = clip_space * vec2(1, -1);

    gl_Position = vec4(v_pos, 0, 1);
}
`

const fragmentSource = `
precision mediump float;

varying vec2 v_pos;

void main() {
    vec2 color = v_pos * 0.5 + 0.5;
    gl_FragColor = vec4(color, 1, 1);
}
`

export async function initWebgl() {
    const div = document.getElementById('app')

    const canvas = document.createElement("canvas")
    canvas.width = 300
    canvas.height = 200

    let gl = canvas.getContext("webgl")
    if (!gl) {
        console.error("不支持webgl")
        return;
    }

    let vertexShader = createShader(gl, gl.VERTEX_SHADER, vertexSource);
    let fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fragmentSource);
    let program = createProgram(gl, vertexShader, fragmentShader);

    let positionAttributeLocation = gl.getAttribLocation(program, "a_position");

    let positionBuffer = gl.createBuffer()!
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
    gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
        0, 0,
        0, 100,
        100, 0,
    ]), gl.STATIC_DRAW);

    gl.useProgram(program);

    let aCoordLocation = gl.getUniformLocation(program, "a_rect");
    gl.uniform2f(aCoordLocation, canvas.width, canvas.height);

    gl.enableVertexAttribArray(positionAttributeLocation)
    gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer)

    gl.vertexAttribPointer(positionAttributeLocation, 2, gl.FLOAT, false, 0, 0);

    // gl.viewport(0, 150, 100, 50);
    gl.drawArrays(gl.TRIANGLES, 0, 3);

    div?.append(canvas)
}